<script setup lang='ts'>
import { getVideo } from '@/api/index'
import { ref, onMounted, onUnmounted, nextTick, useTemplateRef, watch } from 'vue'

const videoList = ref([])
const offset = ref(0)

getVideo().then((res) => {
  videoList.value = res.data.data.feeds.map(video => ({
    ...video,
    isPlaying: false  // 初始状态为 false
  }));
});

const active = ref(0)

// 触底
const loading = ref(false)
const finished = ref(false)

const onLoad = () => {
  // 异步更新数据
  loading.value = true // 开始加载数据
  getVideo(offset.value).then((res) => {
    if (videoList.value) {
      videoList.value = [...videoList.value, ...res.data.data.feeds]
      loading.value = false
      offset.value = offset.value + 10
      // 如果已经加载完所有数据
      if (videoList.value.length >= 100) {
        finished.value = true
      }
    }
  })
}

// 播放视频
const videosRef = useTemplateRef('videos')
console.log(videosRef)

// 创建 IntersectionObserver 并观察视频元素
const observer = new IntersectionObserver(
  (entries) => {
    entries.forEach((entry) => {
      const video = entry.target;
      const videoIndex = videoList.value.findIndex(v => v.video?.url === video.dataset.src);
      if (videoIndex !== -1) {
        if (entry.isIntersecting) {
          video.src = video.dataset.src;
          video.play();
          nextTick(()=>{
            videoList.value[videoIndex].isPlaying = true;
          })
        } else {
          video.pause();
          videoList.value[videoIndex].isPlaying = false;
        }
      }
    });
  },
  {
    threshold: 1, // 视频全部可见时才开始播放
  }
);

onMounted(() => {
  // 使用 nextTick 确保在 DOM 更新后执行
  // 为每个视频元素添加 IntersectionObserver
  nextTick(() => {
    setTimeout(() => {
      videosRef.value?.forEach((video) => {
        observer.observe(video)
      })
    }, 1000)
  })
})

onUnmounted(() => {
  // 组件卸载时，停止观察所有视频元素
  nextTick(() => {
    setTimeout(() => {
      videosRef.value?.forEach((video) => {
        observer.unobserve(video)
      })
    }, 1000)
  })
})

// 视频播放 / 停止
const togglePlay = (index) => {
  if (videoList.value[index].isPlaying) {
    videosRef.value[index].pause();
  } else {
    videosRef.value[index].play();
  }
  videoList.value[index].isPlaying = !videoList.value[index].isPlaying;
};
</script>

<template>
  <div v-if="videoList">
    <!-- <button @click="xxx">touch me</button> -->
    <van-tabs v-model:active="active" animated>
      <van-tab v-for="tab in ['推荐', '热片解读', '新品预告']" :title="tab" :key="tab">
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
          <!-- 绑定 ref="videoElements" 到容器上 -->
          <div v-for="(video, index) in videoList" :key="video.id" class="video">
            <div class="item">
              <p class="title">{{ video.title }}</p>
              <!-- 为每个视频元素添加 ref 和 data-src -->
              <video controls class="video-player" ref="videos" :poster="video.images[0]?.url" muted
                :data-src="video.video?.url"></video>
              <div class="playIcon" @click="togglePlay(index)">
                <van-icon :name="video.isPlaying ? '' : 'play-circle-o'" size="60" color="#fff" />
              </div>
            </div>
            <div class="user">
              <div class="userInfo">
                <img :src="video.user.avatarurl" alt="" />
                <span>{{ video.user.nickName }}</span>
              </div>
              <div class="icon">
                <div class="iconItem">
                  <van-icon name="good-job-o" size="20" color="#777" />
                  <span>{{ video.upCount }}</span>
                </div>
                <div class="iconItem">
                  <van-icon name="chat-o" size="20" color="#777" />
                  <span>{{ video.commentCount }}</span>
                </div>
                <div class="iconItem">
                  <van-icon name="share-o" size="20" color="#777" />
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<style lang="less" scoped>
.video {
  .item {
    width: 100vw;
    position: relative;

    .title {
      position: absolute;
      font-size: 17rem;
      color: #fff;
      top: 0;
      left: 0;
      padding: 8rem 12rem;
      margin: 0;
      // background: linear-gradient(to bottom, #6464648e 0%, rgba(255, 255, 255, 0) 100%);

    }

    video {
      width: 100%;
      height: 52vh;
      background: #000;
    }

    .playIcon {
      position: absolute;
      top: 45%;
      left: 40%;
    }
  }

  .user {
    display: flex;
    justify-content: space-between;
    padding: 14rem;

    .userInfo {
      display: flex;
      align-items: center;

      img {
        width: 20rem;
        height: 20rem;
        border-radius: 50%;
        margin-right: 8rem;
      }
    }

    .icon {
      display: flex;
      align-items: center;

      .iconItem {
        margin-left: 20rem;
        display: flex;
        align-items: center;

        span {
          margin-left: 8rem;
          color: #777;
        }
      }
    }
  }
}
</style>
